<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-06 09:20:07
 * @Last Modified time: 2023-02-23 10:23:17
 */
namespace app\api\services\store;

use app\common\services\store\DiyPageService as CommonDiyPageService;
use frank\utils\helper\ArrayHelper;
use app\common\services\store\GoodsService;
use app\common\services\store\CartService;

/**
 * 
 * Class DiyPageService
 */
class DiyPageService extends CommonDiyPageService
{


    /**
     * 获取首页
     */
    public function getApiHome($user){
        $detail = $this->getHome();
        return $this->getDataItems(ArrayHelper::objectToArray($detail),$user);
    }

    private function getDataItems($detail,$user){
        // dump($items);die;
        foreach ($detail['page_data']['items'] as $key => &$item) {
            if (!empty($item['type']) && $item['type'] === 'goods') {
                $item['data'] = $this->getGoodsList( $item ,$user);
            }elseif (!empty($item['type']) && $item['type'] === 'coupon') {

            }elseif (!empty($item['type']) && $item['type'] === 'seckill') {

            }
        }
        return $detail;
    }



    /**
     * 商品组件：获取商品列表
     */
    public function getGoodsList($item,$user)
    {
        $goodsService =  GoodsService::instance();


        if($item['params']['source'] === 'auto') {
            // 数据来源：自动
            $goodsList = $goodsService->getGoodsListAsWith([],-1,0,[],[],[
                'sortType' => $item['params']['sort'],
                'listRows' => $item['params']['limit']
            ])->hidden(['content']);
        }elseif ($item['params']['source'] === 'choice') {
            // 数据来源：手动选择
            $goodsIds = array_column($item['data'], 'goods_id');
            $goodsList = $goodsService->dao->getGoodsListAsWith(['id'=>$item['params']['goods_id']],-1,0,[])->hidden(['content']);
        } 
        if ($goodsList->isEmpty()) return [];
        // 格式化商品列表
        $cartService = CartService::instance()->init($user);
        foreach ($goodsList as &$goods) {
            $goods['goods_cart_count'] = $cartService->getGoodsNum((int)$goods['id']);
            $goods['goods_sku_id'] = $goods['spec_type']['value'] == 1? $goods['sku'][0]['id'] : 0;
            unset($goods['sku']);
        }
        return $goodsList;
    }


}
